package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.demo.DBmake.PostgreDB;
import com.example.demo.JsonObj.FriendObj;
import com.example.demo.Utils.JsonUtil;
import com.example.demo.Utils.TokenUtil;
import com.example.demo.api.CommonResult;
import com.example.demo.entity.FriInfo;
import com.example.demo.entity.MessInfo;
import com.example.demo.entity.UpdInfo;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


@RestController
public class FriController {
    @RequestMapping(value = "/AddFri",method = RequestMethod.POST)
    public CommonResult login(@RequestBody FriInfo friInfo){

        String token = friInfo.getToken();
        if(token.equals(""))  return CommonResult.unauthorized("登录过期");
        if(!TokenUtil.verify(token)) return CommonResult.unauthorized("登录过期");

        String FriendName = friInfo.getUsername();
        int MyUid = friInfo.getUid();
//        System.out.println(Uid);
        PostgreDB Target = new PostgreDB();


        if(Target.CheckUsername(FriendName)) return  CommonResult.validateFailed();

        int FriUid=Target.GetUid(FriendName);

        if(FriUid == -1) return CommonResult.validateFailed();

        String MyFriList = Target.GetFriJson(MyUid);
        String ToFriList = Target.GetFriJson(FriUid);
        String FirNickname = Target.GetNickname(FriUid);
        String MyNickname = Target.GetNickname(MyUid);
        String MyUsername = Target.GetUsername(MyUid);
//        System.out.println(FriList);
        if(MyFriList == null || ToFriList == null || FirNickname == null || MyNickname == null || MyUsername == null) return CommonResult.validateFailed();


        String MyFriendListJson = JsonUtil.AddFriend(MyFriList,FriUid,FriendName,FirNickname);
        String ToFriendListJson = JsonUtil.AddFriend(ToFriList,MyUid,MyUsername,MyNickname);

        if(MyFriendListJson == null || ToFriendListJson == null) return CommonResult.failed();
//        System.out.println(FriendJson);
        String sql1 = "UPDATE public.usercom SET friend_list = '"+MyFriendListJson+"' WHERE uid = "+MyUid;
        String sql2 = "UPDATE public.usercom SET friend_list = '"+ToFriendListJson+"' WHERE uid = "+FriUid;
//        System.out.println(sql);

        if(!Target.updateItem(sql1) || !Target.updateItem(sql2)) return CommonResult.ErrorDateBase();

        token = TokenUtil.sign(MyUid);
        return CommonResult.success(MyUid,token);
    }
}
